<template>
  <div class="search-dialog">
    <el-dialog

      :visible.sync="drawer"
      width="80%"
      :show-close="false"
      :before-close="handleClose"
      top="50px"
    >
      <template slot="title">
        <div class="dialog-title">
          <span class="dialog-text">搜索</span>
          <div class="button-right">
            <span class="title-close" @click="cancel">
              <img src="../../assets/images/xxx.png" alt="">
            </span>
          </div>
        </div>
      </template>

      <div>
        <div class="search-main">
          <div style="text-align: center; margin-top: 20px">
            <el-input
              ref="search"
              v-model="search.cardName"
              class="inputCalss"
              style="width: 50%"
              placeholder="请输入搜索内容"
              suffix-icon="el-icon-search"
              @keyup.native.enter="searchBulr"
            />
            <el-button
              type="primary"
              style="margin-left: 16px"
              class="searchBtn"
              icon="el-icon-search"
              @click="searchBulr"
            >搜索
            </el-button>
          </div>
          <div
            class="his-wrap"
            style="
              display: flex;
              flex-wrap: wrap;
              margin-left: 21.5%;
              height: 32px;
              margin-top: 10px;
              margin-right: 30%;
              overflow-x: auto;
            "
          >
            <div
              v-for="(tag, index) in dynamicTags"
              :key="index"
              class="history-text"
              @click="tagsClick(tag)"
            >
              {{ tag }}
            </div>
          </div>
          <div style="position: absolute; margin-left: 71%; margin-top: -30px">
            <span class="tagsIcon" @click="clearHistory">清空</span>
          </div>
          <div style="margin-top: 10px; margin-bottom: 15px">
            <el-menu
              :default-active="cardSort"
              style="
                display: flex;
                border-top: 1px solid #e6e6e6;
                padding-left: 24px;
                height: 45px;
              "
              class="el-menu-demo"
              mode="horizontal"
              @select="handleSelect"
            >
              <el-menu-item index="1">指标</el-menu-item>
              <el-menu-item index="2">分析</el-menu-item>
              <el-menu-item index="3">报表</el-menu-item>
              <!-- <el-menu-item index="4">模型</el-menu-item> -->
              <!-- 1指标 2分析 3报表 4模型 5业务） -->
            </el-menu>
          </div>
          <div class="main">
            <template>
              <div
                style="
                  display: flex;
                  flex-wrap: nowrap;
                  align-items: center;
                  padding-left: 10px;
                "
              >
                <div class="selectWidth selectLine">
                  <div style="display: flex">
                    <span
                      class="selectTitle"
                      style="padding-top: 7px"
                    >归属组织：</span>
                    <Treeselect
                      v-model="search.orgId"
                      :multiple="false"
                      style="width: 220px; color: #72767b; margin-left: 10px"
                      :default-expand-level="1"
                      :flat="true"
                      placeholder="请选择组织"
                      :normalizer="normalizer"
                      :options="optionsOrg"
                      @input="queryPageData(1)"
                    />
                  </div>
                </div>
                <div class="selectWidth selectLine">
                  <span class="selectTitle">订阅：</span>
                  <el-select
                    v-model="search.subscribeFlag"
                    clearable
                    class="selectLine"
                    placeholder="请选择"
                    @change="queryPageData(1)"
                  >
                    <el-option
                      v-for="item in readList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>

                <div v-if="cardSort === '1'" class="selectWidth selectLine">
                  <span
                    class="selectTitle"
                    style="margin-right: 10px"
                  >时间:</span>
                  <el-select
                    v-model="granularity"
                    clearable
                    placeholder="请选择时间粒度"
                    style="width: 220px"
                    @change="queryPageData(1)"
                  >
                    <el-option
                      v-for="item in granularityOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
                <div v-if="cardSort === '1'" class="selectWidth selectLine">
                  <span class="selectTitle">分类：</span>
                  <el-select
                    v-model="category"
                    clearable
                    style="width: 220px"
                    placeholder="请选择分类"
                    @change="queryPageData(1)"
                  >
                    <el-option
                      v-for="item in categoryList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </div>
              <div class="table-wrap">
                <el-table
                  v-loading="tableLoading"
                  :data="tableData"
                  style="width: 100%; margin-top: 15px"
                  height="450px"
                  :border="true"
                  :stripe="false"
                >
                  <el-table-column
                    :prop="indexName.key"
                    :label="indexName.name"
                  >
                    <template slot-scope="scope">
                      <a class="zl-link" @click="getDetail(scope.row)">{{
                        scope.row.cardName
                      }}</a>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-for="(item, index) in tableTitle"
                    :key="index"
                    :prop="item.key"
                    :label="item.name"
                  />
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <div style="display: flex; align-items: center">
                        <div class="tabWidth">
                          <div
                            v-if="scope.row.subscribeFlag === '1'"
                            class="zl-inline"
                            @click="subClick(false, scope.row.cardId)"
                          >
                            <img
                              src="../../assets/images/read.png"
                              alt=""
                              class="read-img"
                            >
                            <span class="read-btn">取消订阅</span>
                          </div>
                          <div
                            v-if="scope.row.subscribeFlag === '0'"
                            class="zl-inline"
                            @click="subClick(true, scope.row.cardId)"
                          >
                            <img
                              src="../../assets/images/onRead.png"
                              alt=""
                              class="read-img"
                            >
                            <span class="read-btn">订阅</span>
                          </div>
                          <div class="zl-inline" @click="getDetail(scope.row)">
                            <!-- <img src="../../assets/images/onRead.png" alt="" class="read-img"> -->
                            <i class="el-icon-s-operation read-img" />
                            <span class="read-btn">详情</span>
                          </div>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="pageClass">
                <el-pagination
                  :current-page="pageNum"
                  :page-sizes="[20, 40, 60, 80]"
                  class="paginaClass"
                  :page-size="pageSize"
                  layout="total, prev, pager, next, sizes, jumper"
                  :total="total"
                  @size-change="changePageSize"
                  @current-change="changePage"
                />
              </div>
            </template>
          </div>
        </div>
      </div>
    </el-dialog>
    <zl-card-detail ref="detail" />
    <zl-modal-dialog ref="modal" />
    <el-dialog title="详情" :visible.sync="iframeVisible" width="1200px">
      <zl-iframe ref="iframe" :href="frameHref" height="800px" />
    </el-dialog>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import Treeselect from "@riophae/vue-treeselect";
import mixin from "./../../utils/mixin.js";
import { cloneDeep } from "lodash";
import { subject } from "../../registerApps";
import { cardDetail, modalDialog, iframe } from '@zl/product'

export default {
  components: {
    Treeselect,
    zlCardDetail: cardDetail,
    zlModalDialog: modalDialog,
    zlIframe: iframe
  },
  mixins: [mixin],
  data() {
    return {
      searchValue: '',
      cardSort: '1',
      mainShow: true,
      dynamicTags: [],
      optionsOrg: [],
      drawer: false,
      search: {
        subscribeFlag: '',
        orgId: ''
      },
      pageNum: 1,
      pageSize: 20,
      total: 0,
      tableLoading: false,
      readList: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '已订阅',
          value: '1'
        },
        {
          label: '未订阅',
          value: '0'
        }
      ],
      category: '',
      granularity: '',
      categoryList: [
        {
          label: '企业',
          value: 'D_QIYE39'
        },
        {
          label: '系列',
          value: 'D_XILIE'
        },
        {
          label: '工区',
          value: 'D_GONGQU'
        },
        {
          label: '电解槽',
          value: 'D_DIANJIEC'
        },
        {
          label: '混合炉',
          value: 'D_HUNHEL'
        },
        {
          label: '脱硫塔',
          value: 'D_TUOLIUT'
        }
      ],
      granularityOptions: [
        {
          label: '日',
          value: 'DAY_DIM'
        },
        {
          label: '月',
          value: 'MONTH_DIM'
        },
        {
          label: '年',
          value: 'YEAR_DIM'
        },
        {
          label: '早班',
          value: 0
        },
        {
          label: '中班',
          value: 1
        },
        {
          label: '晚班',
          value: 2
        }
      ],
      normalizer(node) {
        return {
          id: node.id,
          children: node.child,
          label: node.name
        }
      },
      tIndexListData: [],
      value: '',
      tableData: [],
      tableTitle: [],
      indexName: {},
      frameHref: '',
      iframeVisible: false
    }
  },
  watch: {
    '$route.query.search'(val) {
      this.search.cardName = val
      this.searchBulr()
    }
  },
  mounted() {
  },
  methods: {
    ...mapActions('messageCenter', [
      'cardsubscribe',
      'cardunSubscribe',
      'tIndexList',
      'queryMySearchList',
      'cleanMySearchList',
      'queryComprehensiveCardByPage'
    ]),
    getDetail(card) {
      console.log(card)
      switch (this.cardSort) {
        case '1':
          this.$refs.detail.open(card.cardId)
          break
        case '2':
        case '3':
          this.frameHref = card.cardUrl
          this.iframeVisible = true
          break
        case '4':
          this.$refs.modal.show(card)
          break
        default:
          break
      }
    },
    show() {
      if (this.$route.query.search || this.$route.query.search === '') {
        this.search = {
          cardName: this.$route.query.search
        }
      }
      this.drawer = true
      this.$nextTick(() => {
        this.$refs.search.focus()
      })
      this.getIndexList()
      this.getSearchMyList()
      this.getOrgList()
      this.queryPageData(1)
      this.tableTitleList()
    },
    handleSelect(value) {
      if (value === '1') {
        this.search.orgId = ''
      }
      this.cardSort = value
      if (value === '') {
        this.cardSort = '1'
      }
      this.tableTitleList()
      this.mainShow = false
      this.queryPageData(1)
      this.getOrgList()
    },
    tableTitleList() {
      this.tableTitle = []
      switch (this.cardSort) {
        case '1':
          this.indexName = { name: '指标名称', key: 'cardName' }
          this.tableTitle = [
            { name: '组织', key: 'orgId' },
            { name: '指标说明', key: 'remark' }
            // { name: "当前值", key: "value" },
          ]
          break
        case '2':
          this.indexName = { name: '分析名称', key: 'cardName' }
          this.tableTitle = [
            { name: '组织', key: 'cardOrgRelation' },
            { name: '分析详情', key: 'remark' }
          ]
          break
        case '3':
          this.indexName = { name: '报表名称', key: 'cardName' }
          this.tableTitle = [
            { name: '组织', key: 'cardOrgRelation' },
            { name: '报表详情', key: 'remark' }
          ]
          break
        case '4':
          this.indexName = { name: '模型名称', key: 'cardName' }
          this.tableTitle = [
            { name: '组织', key: 'cardOrgRelation' },
            { name: '模型详情', key: 'remark' }
          ]
          break
        default:
          break
      }
    },
    // 卡片订阅
    subClick(isSub, row) {
      var parms = {
        cardId: row
      }

      if (isSub) {
        this.cardsubscribe(parms)
          .then((res) => {
            if (res.data.code !== '0') {
              return
            }
            this.$message.success('订阅成功')
            subject.next({
              type: 'parent',
              payload: {
                setSubCount: true
              }
            })

            this.queryPageData(1)
          })
          .catch((err) => {
            console.log(err)
            this.loading = false
          })
      } else {
        this.cardunSubscribe(parms)
          .then((res) => {
            if (res.data.code !== '0') {
              return
            }
            this.$message.success('取消订阅成功')
            subject.next({
              type: 'parent',
              payload: {
                setSubCount: true
              }
            })
            this.queryPageData(1)
          })
          .catch((err) => {
            console.log(err)
            this.loading = false
          })
      }
    },
    async getOrgList() {
      // var orgList = []
      let cons = cloneDeep(this.$store.state.sys.orgs)

      if (this.cardSort === '1') {
        cons = cloneDeep(this.$store.state.sys.indexOrgs)
        cons = {
          id: '',
          name: '全部',
          child: cons
        }
      }
      this.optionsOrg = [cons]
    },
    // 获取板块
    getIndexList() {
      this.tIndexList()
        .then((res) => {
          if (res.data.code !== '0') {
            return
          }
          this.tIndexListData = res.data.data
        })
        .catch((err) => {
          console.log(err)
          this.loading = false
        })
    },
    // 查询我的历史记录
    getSearchMyList() {
      this.queryMySearchList()
        .then((res) => {
          if (res.data.code !== '0') {
            return
          }
          this.dynamicTags = res.data.data
        })
        .catch((err) => {
          console.log(err)
          this.loading = false
        })
    },
    handleClose(tag) {
      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      this.drawer = false
      this.search.cardName = ''
    },
    // 输入框搜索事件
    searchBulr() {
      if (this.cardSort === '') {
        this.cardSort = '1'
      }
      this.mainShow = false
      this.tableTitleList()
      this.queryPageData(1)
    },
    tagsClick(value) {
      this.mainShow = false
      this.cardSort = '1'
      this.$set(this.search, 'cardName', value)
      this.tableTitleList()
      this.queryPageData(1)
    },
    // 修改页码
    changePage(val) {
      this.pageNum = val
      this.queryPageData()
    },
    // 修改每页长度
    changePageSize(val) {
      this.pageSize = val
      this.queryPageData(1)
    },
    // 搜索事件
    queryPageData(page) {
      if (page) {
        this.pageNum = page
      }
      if (this.cardSort === '') {
        return
      }
      this.tableLoading = true
      const search = {}
      // 过滤空数据
      if (this.cardSort === '1') {
        if (this.category) {
          search.typeCode = this.category
        }
        if (this.granularity) {
          search.granularity = this.granularity
        }
      }
      for (const item in this.search) {
        const searchItem = this.search[item]
        if (searchItem) {
          search[item] = searchItem
        }
      }
      var params = {
        ...search,
        noIndexInfo: true,
        cardSort: this.cardSort,
        currPage: this.pageNum,
        pageSize: this.pageSize,
        orgId: search.orgId ? [search.orgId] : []
      }
      this.tableData = []
      this.queryComprehensiveCardByPage(params)
        .then((res) => {
          if (res.data.code !== '0') {
            this.tableLoading = false
            return
          }
          this.tableData = []
          this.tableData = res.data.data.list
          this.tableLoading = false
          this.total = res.data.data.totalCount
        })
        .catch((err) => {
          console.log(err)
          this.tableLoading = false
        })
    },
    clearHistory() {
      this.$confirm('此操作将删除历史记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.cleanMySearchList()
            .then((res) => {
              if (res.data.code !== '0') {
                return
              }
              this.$message({
                type: 'success',
                message: '清除成功!'
              })
              this.dynamicTags = []
            })
            .catch((err) => {
              console.log(err)
              this.loading = false
            })
        })
        .catch(() => {})
    },
    cancel() {
      this.handleClose()
    }
  }
}
</script>
<style lang="scss" scoped>
.search-main {
  height: 100%;
  position: relative;
  /* .el-input__inner {
            height: 60px !important;
        } */
  line-height: 32px;

  .inputCalss {
    margin-top: 10px;
  }

  .main {
    height: calc(100% - 129px);
    background: #fff;
  }

  .tagsMain {
    padding-top: 20px;
    line-height: 50px;
    width: 100%;
  }

  .tagsClass {
    margin-left: 10px;
    height: 40px;
    padding-top: 9px;
    width: 145px;
    text-align: center;
  }

  .tagsTitle {
    font-size: 18px;
    margin-left: 10px;
    font-weight: 800;
    width: 91%;
  }

  .tagsIcon {
    cursor: pointer;
    width: 24px;
    height: 12px;
    font-size: 12px;
    font-family: Source Han Sans CN, Source Han Sans CN-Regular;
    font-weight: 400;
    text-align: LEFT;
    color: #9ba3c2;
  }

  .tableIcon {
    font-size: 22px;
  }

  .tabWidth {
    margin: 0 auto;
  }

  .selectWidth {
    /* width: 33%; */
  }

  .selectLine {
    margin-left: 15px;
  }

  .table-wrap {
    height: calc(98% - 100px);
    margin: 0px 24px;
  }

  .selectTitle {
    font-size: 14px;
    font-family: Source Han Sans CN, Source Han Sans CN-Regular;
    font-weight: 400;
    text-align: LEFT;
    color: #62687f;
    line-height: 20px;
  }
  .his-wrap {
    &::-webkit-scrollbar-track-piece {
      background: #d3dce6;
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #99a9bf;
      border-radius: 20px;
    }
  }
  .history-text {
    font-size: 12px;
    font-family: Source Han Sans CN, Source Han Sans CN-Regular;
    font-weight: 400;
    text-align: LEFT;
    color: #62687f;
    margin-left: 10px;
    cursor: pointer;
  }

  .read-btn {
    font-size: 14px;
    font-weight: 400;
    text-align: LEFT;
    color: #3b6cf1;
    margin-left: 5px;
    cursor: pointer;
    vertical-align: middle;
  }

  .read-img {
    vertical-align: middle;
    margin-top: -4px;
  }
}
.w100 {
  width: 200px;
}
.search-dialog {
  width: 0;
  .button-right {
    float: right;
    margin: 3px 10px;
    line-height: 30px;
    color: #62687f;
    cursor: pointer;
  }

  .dialog-title {
    font-size: 16px;
    font-family: Source Han Sans CN, Source Han Sans CN-Medium;
    font-weight: 550;
    text-align: LEFT;
    color: #252631;
    line-height: 24px;
    background-color: #e9ecf7;
  }

  .dialog-text {
    font-size: 14px;
    font-family: Source Han Sans CN, Source Han Sans CN-Medium;
    font-weight: 550;
    text-align: LEFT;
    color: #252631;
    line-height: 35px;
    margin: 24px;
  }

  .el-dialog__header {
    padding: 0px 0px 0px 0px !important;
  }

  .el-dialog__body {
    padding: 0px 0px 0px 0px !important;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .el-menu--horizontal > .el-menu-item.is-active {
    border-bottom: 2px solid #3b6cf1;
    color: #3b6cf1 !important;
    height: 45px;
  }

  .el-menu--horizontal > .el-menu-item {
    float: left;
    height: 60px;
    line-height: 45px;
    margin: 0;
    border-bottom: 2px solid transparent;
    color: #252631;
    height: 45px;
  }

  .pageClass {
    text-align: right;
    margin: 15px 0px 24px 0px;
    border-top: 1px solid #e9ecf7;
  }

  .paginaClass {
    height: 50px;
    padding-top: 10px;
    padding-right: 24px;
  }
}
.zl-inline {
  display: inline-block;
  margin-left: 8px;
}
</style>
